package com.yqr.mapper;

import com.github.pagehelper.PageInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import tk.mybatis.mapper.autoconfigure.MapperAutoConfiguration;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;
import java.util.Properties;

 /**
     * @Title: ${NAME}
     * @ProjectName ${PROJECT_NAME}
     * @Description: TODO
     * @author Mr.Qian
     * @date ${DATE}${TIME}
     */
@Slf4j
@Configuration
@AutoConfigureBefore(MapperAutoConfiguration.class)
@MapperScan(value = "com.yqr.*.persistence", sqlSessionFactoryRef = "sqlSessionFactory", properties = {
        "mappers=com.yqr.mapper.MyMapper",
        "style=normal",
        "enumAsSimpleType=true",
        "notEmpty=true"
})

public class MybatisAutoConfiguration {
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
        try {
            final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/yqr/*/persistence/xml/**/*.xml"));
            
            // pageHelper
            Interceptor interceptor = new PageInterceptor();
            Properties properties = new Properties();
            properties.setProperty("helperDialect", "mysql");
            properties.setProperty("reasonable", "true");
            interceptor.setProperties(properties);
            sessionFactory.setPlugins(new Interceptor[]{interceptor});
            
            return sessionFactory.getObject();
        } catch (Exception e) {
            log.error("配置 数据源 的SqlSessionFactory失败", e);
            throw new RuntimeException(e.getMessage());
        }
    }


}
